/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.jg.report.freight.information.constant.enums.ReportDocTypeEnum;
import org.jeecg.modules.third.jg.report.freight.information.dto.AppInfoDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.DriverDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.VehicleDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.financial.FinancialDTO;
import org.jeecg.modules.third.jg.report.freight.information.dto.shippingnote.ShippingNoteDTO;
import org.jeecg.modules.third.jg.report.freight.information.model.R;
import org.jeecg.modules.third.jg.report.freight.information.service.SdReportPlatformService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.report.impl
 * @Author: duanlikao
 * @CreateTime: 2023-03-08 10:14
 * @Description:
 * @Version: 1.0
 */
@Service
public class SdongReportService implements IReportService {
    @Resource
    private BaseReportService baseReportService;


    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;


    @Resource
    private IHyDriverReportService hyDriverReportService;


    @Resource
    private IHyVehicleReportService vehicleReportService;


    @Autowired
    private SdReportPlatformService sdReportPlatformService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Override
    public ReportPlatformEnum getReportType() {
        return ReportPlatformEnum.REPORT_PLATFORM_SD;
    }

    @Override
    public void checkReport() {
        HyConfig config = HyConfigUtils.getConfig();
        if(config == null){
            throw new JeecgBootException("未找到参数配置信息,请联系管理员!");
        }
        //山东监管平台
        if(!config.getSdReportIzUse()){
            throw new JeecgBootException("山东监管平台未配置参数!");
        }
    }

    @Override
    public AppInfoDTO getAppInfo() {
        return null;
    }

    @Override
    public boolean report(HyShippingNote hyShippingNote) {
        if(hyShippingNote == null){
            return false;
        }
        if(this.upDriverAndVehicle(hyShippingNote.getDriverId(),hyShippingNote.getVehicleId())  ){
            if (this.uploadSdShippingNote(hyShippingNote)) {

                return   this.uploadSdCapitalFlow(hyShippingNote.getId());
            }

        }
        return false;
    }

    @Override
    public Result reportShippingNote(HyShippingNote hyShippingNote) {
        return null;
    }

    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote) {
        return null;
    }

    public boolean uploadSdCapitalFlow(String shippingId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);
        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(queryWrapper);

        if(CollectionUtils.isEmpty(shippingNoteBills)) {
            throw new JeecgBootException("未找到对应数据");
        }

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingId);
        FinancialDTO financialDTO = baseReportService.getFinancialDTO(shippingNoteBills,hyShippingNote);
        String jsonString = "";
        if(financialDTO != null){
            jsonString =   JSONObject.toJSONString(financialDTO);
        }
        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_ZJ.getCode();
        ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);
        try{
            String reportResult = sdReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if(StringUtils.isNotEmpty(reportResult)){
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  result.getCode() == 1001 ?  true : false;
                for(HyShippingNoteBill shippingNoteBillDb:shippingNoteBills){
                    shippingNoteBillDb.setUploadStatus(res ?  "1" : "2");
                    shippingNoteBillDb.setUploadDate(new Date());
                    shippingNoteBillDb.setReportFailureReason(res ?  "" : result.getMessage()+result.getData());
                    shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
                }
                hyShippingNoteBillService.updateBatchById(shippingNoteBills);
                return res;
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            for(HyShippingNoteBill shippingNoteBillDb:shippingNoteBills){
                shippingNoteBillDb.setUploadStatus( "2");
                shippingNoteBillDb.setUploadDate(new Date());
                shippingNoteBillDb.setReportFailureReason(e.getMessage());
                shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
            }
            hyShippingNoteBillService.updateBatchById(shippingNoteBills);
        }
        return  false;
    }

    public boolean uploadSdShippingNote(HyShippingNote hyShippingNote) {
        HyShippingNote ShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        if("1".equals(ShippingNoteDb.getUploadStatus())){
            return true;
        }
        try{
            if(!"2".equals(hyShippingNote.getUploadStatus())) {
                baseReportService.checkShippingNoteRoute(hyShippingNote);
            }

            String jsonString = "";
            ShippingNoteDTO shippingNoteDTO = baseReportService.shippingNoteTOShippingNoteDTO(ShippingNoteDb, hyShippingNote.getCompanyId());
            if (shippingNoteDTO != null) {
                jsonString = JSONObject.toJSONString(shippingNoteDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_YD.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

            String reportResult = sdReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean res = result.getCode() == 1001  ? true : false;
                ShippingNoteDb.setUploadStatus(res ? "1" : "2");
                ShippingNoteDb.setUploadDate(new Date());
                ShippingNoteDb.setReportFailureReason(res ? "" : result.getMessage()+result.getData());
                ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
                hyShippingNoteService.updateById(ShippingNoteDb);
                return res;
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportFailureReason(e.getMessage());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
            hyShippingNoteService.updateById(ShippingNoteDb);
        }

        return  false;
    }

    /**
     * 按运单上传司机和车辆信息
     * @param driverId
     * @param vehicleId
     */

    private boolean upDriverAndVehicle(String driverId,String vehicleId) {

        boolean  resDriver = hyDriverReportService.checkUploadStatus(driverId ,ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
        boolean  resVehicle = vehicleReportService.checkUploadStatus(vehicleId , ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());

        if(resDriver && resVehicle){
            return true;
        }

        if(!resDriver){
            resDriver = this.uploadDriver(driverId);
        }
        if(!resVehicle){
            resVehicle =   this.uploadVehicle(vehicleId) ;
        }
        return resDriver && resVehicle ;
    }

    /**
     * 平台司机上报
     *
     * @param driverId
     * @return
     */
    public boolean uploadDriver(String driverId) {
        HyDriver hyDriverDb = driverService.getById(driverId);
        if (hyDriverDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        //if (hyDriverReportService.checkUploadStatus(driverId ,ReportPlatformEnum.REPORT_PLATFORM_HB.getCode())) {
        //    throw new JeecgBootException("该司机已经上传过，请勿重复上传");
        //}
        HyDriverReport hyDriverReport = new HyDriverReport();
        try {

            //人员从业资格证验证
            if(!driverService.checkQualificationV2(hyDriverDb)){
                throw new JeecgBootException("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
            }

            String jsonString = "";
            DriverDTO driverDTO = baseReportService.hyDriverTODriverDTO(hyDriverDb);
            if (driverDTO != null) {
                jsonString = JSONObject.toJSONString(driverDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_JSY.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);

            String reportResult = sdReportPlatformService.sendReport(reportDocTypeEnum, jsonString);
            if (StringUtils.isNotEmpty(reportResult)) {
                R result = JSON.parseObject(reportResult, R.class);
                boolean  res = result.getCode() == 1001 && result.isSuccess() ? true : false;
                hyDriverReport.setId(driverId);
                hyDriverReport.setDriverId(driverId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
                hyDriverReport.setDriverUploadStatus(res ? "1" : "2");
                hyDriverReport.setUploadDate( new Date() );
                hyDriverReport.setDriverReportFailureReason(result.getMsg()+result.getData() );
                return hyDriverReportService.saveDriverReport(hyDriverReport);
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            hyDriverReport.setId(driverId);
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
            hyDriverReport.setDriverUploadStatus( "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason(e.getMessage());
            hyDriverReportService.saveDriverReport(hyDriverReport);
        }

        return  false;
    }

    public boolean uploadVehicle(String vehicleId) {
        HyVehicle hyVehiclDb = vehicleService.getById(vehicleId);
        if(hyVehiclDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        //if(vehicleReportService.checkUploadStatus(vehicleId , ReportPlatformEnum.REPORT_PLATFORM_HB.getCode())  ) {
        //    throw new JeecgBootException("该车辆已经上传过，请勿重复上传");
        //}
        HyVehicleReport hyVehicleReport = new HyVehicleReport();
        try {
            if(StringUtils.isEmpty(hyVehiclDb.getRoadTransportNumber())){
                throw new JeecgBootException("车辆道路运输证不能为空！");
            }
            if(StringUtils.isBlank(hyVehiclDb.getTrailerVehiclePlateNumber())){

                throw new JeecgBootException("车辆挂车牌号不能为空！");
            }
            if(!hyVehiclDb.getTrailerVehiclePlateNumber().endsWith("挂")){
                throw new JeecgBootException("车辆挂车牌号不正确！");
            }
            if(!vehicleService.checkRTCNoV2(hyVehiclDb)){
                throw new JeecgBootException("车辆道路运输证号不正确或者已过期，请修改后重新上传！");
            }

            HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehiclDb.getVehicleType());
            if(hyVehicleType == null ){
                throw new JeecgBootException("车辆类型不存在,修改后请重新上报！");
            }
            hyVehiclDb.setVehicleType( hyVehicleType.getValue());
            String jsonString = "";
            VehicleDTO vehicleDTO = baseReportService.hyVehicleDTOTOVehicleDTO(hyVehiclDb);
            if(vehicleDTO != null){
                jsonString =   JSONObject.toJSONString(vehicleDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
            ReportDocTypeEnum reportDocTypeEnum = ReportDocTypeEnum.getReportDocTypeEnumByVal(reporDocType);


            String reportResult = sdReportPlatformService.sendReport(reportDocTypeEnum,jsonString);
            if(StringUtils.isNotEmpty(reportResult)){
                R result = JSON.parseObject(reportResult, R.class);
                boolean res =  result.getCode() == 1001 && result.isSuccess() ?  true : false;
                hyVehicleReport.setId(vehicleId);
                hyVehicleReport.setVehicleId(vehicleId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
                hyVehicleReport.setVehicleUploadStatus(res ? "1" : "2");
                hyVehicleReport.setUploadDate( new Date() );
                hyVehicleReport.setVehicleReportFailureReason(result.getMsg()+result.getData());
                return  vehicleReportService.saveVehicleReport(hyVehicleReport);
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            hyVehicleReport.setId(vehicleId);
            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_SD.getCode());
            hyVehicleReport.setVehicleUploadStatus( "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(e.getMessage());
            vehicleReportService.saveVehicleReport(hyVehicleReport);
        }

        return  false;
    }


}
